<?php

class Jf_Controller_Action_Backend extends Jf_Controller_Action_Abstract {

    protected $_modelName = '';

    protected $_perPage = 15;

    protected $_listParams = null;

    protected $_listWhere = array();

    protected $_listAttributes = '*';

    protected $_rowData = array();

    protected $_listParamsNeeds = array();

    protected $_listIndexCols = array();

    protected $_denyAction = array();

    protected $_enbleLoginCheck = true;

    protected function deny () {
        $request = $this -> getRequest ();
        $action = $request -> getActionName ();
        if (in_array ($action, $this -> _denyAction)) {
            throw new Zend_Exception ('对不起，此动作被禁止访问。');
        }
    }

    public function indexAction () {
        $this -> getDispatcher () -> disableView ();
        $this -> forward ('list');
    }

    public function searchAction () {
        $params = $this -> _request -> getParams ();
        if (isset ($params['type']) && isset ($params['keyword'])) {
            $type = $params['type'] . " LIKE ?";
            $params[$type] = '%' . $params['keyword'] . '%';
        }
        unset ($params['type']);
        unset ($params['keyword']);
        unset ($params['ordertrade']);
        unset ($params['orderprice']);
        $page = 1;
        if (isset ($params['page'])) {
            $page = $params['page'];
            unset ($params['page']);
        }
        if ($this -> _request -> getParam ('trash', 0)) {
            $this -> forwardAction ('trash', array('query' => $params, 'page' => $page));
        } else {
            $this -> forwardAction ('list', array('query' => $params, 'page' => $page));
        }
        $this -> getView () -> action = 'search';
        $this -> getDispatcher () -> disableView ();
    }

    protected function getListViewNeeds () {}

    protected function getViewNeeds () {}

    protected function getListParamsNeeds () {
        return $this -> _listParamsNeeds;
    }

    public function listAction () {
        $request = $this -> getRequest ();
        $page = $request -> getParam ('page', 1);
        $query = $request -> getParam ('query', array());
        $params = array();
        if (isset ($this -> _listParams)) {
            foreach ($this -> _listParams as $paramKey) {
                $value = $request -> getParam ($paramKey, null);
                if (isset ($value)) {
                    $params[$paramKey] = $value;
                }
            }
            $this -> getView () -> params = $params;
        }
        $where = array_merge ($params, $query, $this -> _listWhere);
        $orders = array('created_at' => 'desc');
        $attributes = $this -> _listAttributes;
        $model = Jf::getModel ($this -> _modelName);
        $paginator = $model -> getPaginator ($this -> _perPage, $page, $where, $attributes, $orders);
        $this -> getView () -> paginator = $paginator;
        $this -> getListViewNeeds ();
        $this -> renderByAjax ();
    }

    public function trashAction () {
        $request = $this -> getRequest ();
        $query = $request -> getParam ('query', array());
        $pageIndex = $request -> getParam ('page', 1);
        $perPage = $this -> _perPage;
        $offset = ($pageIndex > 0) ? ($pageIndex - 1) * $perPage : 0;
        $query['is_delete'] = 1;
        $paginator = Jf::getModel ($this -> _modelName) -> getPaginator ($offset, $perPage, $query);
        $paginator -> setItemCountPerPage ($perPage) -> setCurrentPageNumber ($pageIndex);
        $this -> getView () -> paginator = $paginator;
        if ($request -> isXmlHttpRequest ()) {
            $this -> renderScript ("$this->_modelName/_content.phtml");
        }
    }

    public function addAction () {
        $request = $this -> getRequest ();
        if ($request -> isPost ()) {
            $validate = Jf::loadValidate ($this -> _modelName);
            $isValid = $validate -> isValid ($request -> getPost ());
            if (is_bool ($isValid)) {
                if (false == $isValid) {
                    return $this -> getResponse () -> setBody (json_encode (array('error' => 1, 'msg' => $validate -> getMessages ())));
                } else {
                    $data = $validate -> getEscaped ();
                }
            } elseif (is_array ($isValid)) {
                $data = $isValid;
            } elseif (is_string ($isValid)) {
                return $this -> getResponse () -> setBody (json_encode (array('error' => 1, 'msg' => $isValid)));
            }
            $data['created_at'] = date ('Y-m-d H:i:s');
            $result = Jf::getModel ($this -> _modelName) -> save ($data);
            if ($result) {
                return $this -> getResponse () -> setBody (json_encode (array('error' => 0, 'msg' => '添加成功')));
            } else {
                return $this -> getResponse () -> setBody (json_encode (array('error' => 1, 'msg' => '添加失败!')));
            }
        } elseif ($request -> isGet ()) {
            $this -> getViewNeeds ();
        }
    }

    public function editAction () {
        $request = $this -> getRequest ();
        $id = (int) $request -> getParam ("id", 0);
        if ( ! $id) {
            throw new Jf_Exception ('缺少ID号');
        }
        $model = Jf::getModel ($this -> _modelName);
        if ($request -> isPost ()) {
            $validate = Jf::loadValidate ($this -> _modelName);
            $isValid = $validate -> isValid ($request -> getPost ());
            if (is_bool ($isValid)) {
                if (false == $isValid) {
                    return $this -> getResponse () -> setBody (json_encode (array('error' => 1, 'msg' => $validate -> getMessages ())));
                } else {
                    $data = $validate -> getEscaped ();
                }
            } elseif (is_array ($isValid)) {
                $data = $isValid;
            } elseif (is_string ($isValid)) {
                return $this -> getResponse () -> setBody (json_encode (array('error' => 1, 'msg' => $isValid)));
            }
            $result = $model -> save ($data, $id);
            if ($result) {
                return $this -> getResponse () -> setBody (json_encode (array('error' => 0, 'msg' => '编辑成功!')));
            } else {
                return $this -> getResponse () -> setBody (json_encode (array('error' => 1, 'msg' => '编辑失败!')));
            }
        } elseif ($request -> isGet ()) {
            $data = Jf::getModel ($this -> _modelName) -> find ($id);
            if (isset ($data['shop_id']) && $data['shop_id']) {
                $data['shop_name'] = Jf::getModel ('shop/shop') -> fetchOne ('shop_name', array('shop_id' => $data['shop_id']));
            }
            $this -> getView () -> data = $data;
        }
    }

    public function saveAction () {
        if ( ! $this -> getRequest () -> isPost ()) {
            return;
        }
        $validate = Jf::loadValidate ($this -> _modelName);
        $isValid = $validate -> isValid ($this -> getRequest () -> getPost ());
        if (false == $isValid) {
            return $this -> getResponse () -> setBody (json_encode (array('error' => 1, 'msg' => $validate -> getMessages ())));
        } else {
            $data = $validate -> getEscaped ();
        }
        $id = $this -> getRequest () -> getParam ("id");
        if ( ! $id) {
            $data['created_at'] = Zend_Date::now () -> get ('YYYY-MM-dd HH:mm:ss');
        }
        $result = Jf::getModel ($this -> _modelName) -> save ($data, $id);
        if ($result) {
            return $this -> getResponse () -> setBody (json_encode (array('error' => 0, 'msg' => '保存成功')));
        } else {
            return $this -> getResponse () -> setBody (json_encode (array('error' => 1, 'msg' => '保存失败!')));
        }
    }

    public function toggleAction () {
        $id = $this -> getRequest () -> getPost ('id');
        $value = $this -> getRequest () -> getPost ('value', 0);
        $type = $this -> getRequest () -> getParam ('type', '');
        $status = ($value > 0) ? 0 : 1;
        $result = Jf::getModel ("$this->_modelName") -> updateByPrimary (array($type => $status), $id);
        if ($result) {
            return $this -> getResponse () -> setBody (json_encode (array('error' => 0, 'msg' => '更新成功!', 'status' => $status)));
        } else {
            return $this -> getResponse () -> setBody (json_encode (array('error' => 0, 'msg' => '更新失败!', 'status' => $status)));
        }
    }

    public function toggleactiveAction () {
        $this -> forwardAction ('toggle', array('type' => 'active'));
    }

    public function togglevisibleAction () {
        $this -> forwardAction ('toggle', array('type' => 'visible'));
    }

    public function deleteAction () {
        $this -> getDispatcher () -> disableView ();
        $id = $this -> getRequest () -> getPost ('id');
        $result = Jf::getModel ($this -> _modelName) -> deleteByPrimary ($id);
        if ($result) {
            return $this -> getResponse () -> setBody (json_encode (array('error' => 0, 'msg' => '删除成功!')));
        } else {
            return $this -> getResponse () -> setBody (json_encode (array('error' => 1, 'msg' => '删除失败!')));
        }
    }

    public function checkAction () {
        $key = $this -> getRequest () -> getParam ('key', null);
        $value = urldecode ($this -> getRequest () -> getParam ("value", null));
        $no_check = $this -> getRequest () -> getParam ("no_check", null);
        $result = array();
        $this -> getDispatcher () -> disableView ();
        if ($key && $value) {
            $model = Jf::getModel ($this -> _modelName);
            $where = array();
            if (isset ($no_check)) {
                $primary = $model -> getPrimary ();
                $where = array("$primary != ?" => $no_check);
            }
            $equal = $model -> checkEqual ($key, $value, $where);
            $result['used'] = $equal;
        } else {
            $result['error'] = true;
        }
        return $this -> getResponse () -> setBody (json_encode ($result));
    }

    public function batchdeleteAction () {
        $data = $this -> getRequest () -> getPost ('data');
        $result = Jf::getModel ($this -> _modelName) -> batchDelete ($data);
        if ($result > 0) {
            return $this -> getResponse () -> setBody (json_encode (array('error' => 0, 'msg' => "删除成功!")));
        } else {
            return $this -> getResponse () -> setBody (json_encode (array('error' => 1, 'msg' => "删除失败!")));
        }
    }

    public function batchSortAction () {
        if ($this -> getRequest () -> isPost ()) {
            $data = $this -> getRequest () -> getPost ('data');
            $model = Jf::getModel ($this -> _modelName);
            $primary = $model -> getPrimary ();
            $insertData = array();
            foreach ($data as $key => $value) {
                $insertData[$key] = array('sort_order' => $value, "$primary" => $key);
            }
            $model -> batchInsert ($insertData, array('sort_order'));
            return $this -> getResponse () -> setBody (json_encode (array('error' => 0, 'msg' => '批量排序成功')));
        }
    }

    public function allSortAction () {
        $result = Jf::getModel ("$this->_modelName") -> update (array('sort_order' => 0), "sort_order != 0");
        if ($result) {
            $this -> getResponse () -> setBody (json_encode (array('error' => 0, 'msg' => "更新成功!")));
        } else {
            $this -> getResponse () -> setBody (json_encode (array('error' => 1, 'msg' => "更新失败!")));
        }
    }

}
